package com.yuandian.customer.perception.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.yuandian.api.customer_perception.po.AdvancedQuery;
import com.yuandian.api.customer_perception.po.StepFunctionRelationParams;
import com.yuandian.api.customer_perception.vo.StepFunctionRelationDetailVo;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.customer.perception.service.IStepFunctionRelationService;
import com.yuandian.enums.TableNameEnum;
import com.yuandian.utils.BeanUtils;
import com.yuandian.utils.ListUtils;
import com.yuandian.utils.PageDataInfo;
import com.yuandian.utils.StringUtils;
import com.yuandian.utils.poi.ExcelTitleUtils;
import com.yuandian.utils.poi.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p> 功能关联度 </p>
 *
 * @Author: LinSheHi
 * @Date: 2022/3/18 9:00
 */
@Slf4j
@RestController
@RequestMapping("/trajectory")
public class StepFunctionRelationController {


    @Autowired
    private IStepFunctionRelationService stepFunctionRelationService;

    /**
     * 查询功能关联度总览
     * @param params
     * @return
     */
    @PostMapping("/getStepFunctionRelationOverview")
    public R getStepFunctionRelationOverview(@RequestBody StepFunctionRelationParams params) {
        if (params.getQueryOperator() == null || params.getStartTime() == null || params.getEndTime() == null) {
            return R.failed("参数不能为空");
        }

        if (ListUtils.isNotNull(params.getAdvancedQuery())) {
            for (AdvancedQuery q : params.getAdvancedQuery()) {
                if (!isNumeric(q.getValue().trim())) {
                    return R.failed("参数格式错误：" + q.getValue());
                }
            }
        }

        return stepFunctionRelationService.getStepFunctionRelationOverview(params);
    }

    /**
     * 需求926查询菜单信息
     * @param params
     * @return
     */
    @PostMapping("/getMenuInfoList")
    public R getMenuInfoList(@RequestBody StepFunctionRelationParams params) {

        return stepFunctionRelationService.getMenuInfoList(params);
    }

    /**
     * 匹配是否为数字
     * @param str 可能为中文，也可能是-19162431.1254，不使用BigDecimal的话，变成-1.91624311254E7
     * @return
     * @author yutao
     * @date 2016年11月14日下午7:41:22
     */
    public static boolean isNumeric(String str) {
        // 该正则表达式可以匹配所有的数字 包括负数
        Pattern pattern = Pattern.compile("-?[0-9]+(\\.[0-9]+)?");
        String bigStr;
        try {
            bigStr = new BigDecimal(str).toString();
        } catch (Exception e) {
            return false;//异常 说明包含非数字。
        }

        Matcher isNum = pattern.matcher(bigStr); // matcher是全匹配
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }


    /**
     * 下载功能关联度总览
     * @param params
     * @param response
     */
    @PostMapping("/getStepFunctionRelationOverviewExcel")
    public void getStepFunctionRelationOverviewExcel(@RequestBody StepFunctionRelationParams params, HttpServletResponse response) {
        if (ListUtils.isNotNull(params.getAdvancedQuery())) {
            for (AdvancedQuery q : params.getAdvancedQuery()) {
                if (!isNumeric(q.getValue().trim())) {
                    log.error("下载功能关联度总览, 参数格式错误：" + q.getValue());
                    return;
                }
            }
        }
        stepFunctionRelationService.getStepFunctionRelationOverviewExcel(params, response);
    }

    /**
     * 查询功能关联度明细
     * @param params
     * @return
     */
    @PostMapping("/getStepFunctionRelationDetail")
    public R getStepFunctionRelationDetail(@RequestBody StepFunctionRelationParams params) {
//        // 设置表名
//        ShardResult shard = tableShardingService
//                .getBpmShardTableNames("busi_step_function_relation", params.getStartTime(), params.getEndTime());
//        if (shard.getCode() != ApiResultCode.SUCCESS.getCode()) {
//            return R.setFail(shard.getCode(), shard.getMessage());
//        }
        List<String> tableNameList = new ArrayList<>();
		tableNameList.add(TableNameEnum.BUSI_STEP_FUNCTION_RELATION.getName());

//        // 获取存在的数据表
//        List<String> existentTableList = TableUtil.removeNoExitTable(tableNameList);
//
//        List<String> noExistentTableList = new ArrayList<>();
//        if (existentTableList.size() != tableNameList.size()) {
//            noExistentTableList = TableUtil.checkNoExistentTable(tableNameList, existentTableList, 8);
//            log.error(noExistentTableList.toString() + " 时间范围超过保存周期!");
//            if (existentTableList.size() <= 0) {
//                return R.setFail(8003, TableUtil.getPrompt(noExistentTableList));
//            }
//        }
        params.setTableNameList(tableNameList);

        PageDataInfo pageDataInfo = stepFunctionRelationService.getStepFunctionRelationDetail(params);

        // 返回结果集
//        if (ListUtils.isNotNull(noExistentTableList)) {
//            return R.ok(HttpStatus.SUCCESS, TableUtil.getPrompt(noExistentTableList), pageDataInfo);
//        }
        return R.ok(pageDataInfo);
    }

    /**
     * 下载功能关联度明细
     * @param params
     * @param response
     */
    @PostMapping("/getStepFunctionRelationDetailExcel")
    public void getStepFunctionRelationDetailExcel(@RequestBody StepFunctionRelationParams params, HttpServletResponse response) {

        ExcelWriter excelWriter = null;
        try {
            // 实例化 ExcelWriter 对象
            excelWriter = EasyExcel.write(response.getOutputStream()).build();
            // 1、查询要导出的数据
            params.setPageNum(1);
            params.setPageSize(-1);
            PageDataInfo pageDataInfo = BeanUtils.cast(getStepFunctionRelationDetail(params).getData());
            List<StepFunctionRelationDetailVo> list = new ArrayList<>();
            if (!Objects.isNull(pageDataInfo)) {
                list = BeanUtils.cast(pageDataInfo.getData());
            }
            //处理数据,分情况回填未知
            for (StepFunctionRelationDetailVo vo : list) {
                if (StringUtils.isEmpty(vo.getOperatorId())) {
                    vo.setOperatorId("-");
                    vo.setOperatorName("-");
                } else if (StringUtils.isEmpty(vo.getOperatorName())) {
                    vo.setOperatorName("未知");
                }

                // 页签名称为空回填'-'
                if (StringUtils.isEmpty(vo.getBeforePageLabelName())) { vo.setBeforePageLabelName("-"); }
                if (StringUtils.isEmpty(vo.getAfterPageLabelName())) { vo.setAfterPageLabelName("-"); }

                // 菜单名称为空回填'-'
                if (StringUtils.isEmpty(vo.getBeforeMenuName())) { vo.setBeforeMenuName("-"); }
                if (StringUtils.isEmpty(vo.getAfterMenuName())) { vo.setAfterMenuName("-"); }

                // URL为空回填'-'
                if (StringUtils.isEmpty(vo.getBeforeUrlApi())) { vo.setBeforeUrlApi("-"); }
                if (StringUtils.isEmpty(vo.getAfterUrlApi())) { vo.setAfterUrlApi("-"); }
            }
            //设置表头
            List<String> headParamsList = new ArrayList<>();
            String title = "功能关联度分析表";
            String fileName = title + System.currentTimeMillis();
            String sheetName = title;
            headParamsList.add(title);
            String formTitleName = ExcelTitleUtils.formTitleName(headParamsList, params.getStartTime(), params.getEndTime());

            List<List<String>> headList = new ArrayList<>();
            List<String> titleList =  Arrays.asList("序号", "用户标识", "用户名", "跳转前URL", "系统名称", "菜单名称", "页签", "跳转后URL", "系统名称", "菜单名称", "页签", "跳转时间");

            titleList.forEach(s -> {
                List<String> childHeadList = new ArrayList<>();
                childHeadList.add(formTitleName);
                childHeadList.add(s);
                headList.add(childHeadList);
            });


//            ExcelUtil.writeExcel(StepFunctionRelationDetailVo.class, fileName, sheetName, list, headList, response);

            ExcelUtil.writeOnly(excelWriter, list, headList, null,
                    StepFunctionRelationDetailVo.class, 0, title);
            // 返回文件流
            ExcelUtil.writeExcel("功能关联度分析表", response);

        } catch (Exception e) {
			R.failed(e.getMessage());
            e.printStackTrace();
        } finally {
            if (excelWriter != null) {
                try {
                    response.getOutputStream().flush();
                    excelWriter.finish();
                    response.getOutputStream().close();
                }catch (Exception e) {
                    log.error("IO流关闭异常： " + e.getMessage());
                }
            }
        }
    }

}
